// pages/upload-document/upload-document.js
Page({
  data: {
    documentType: '',
    documentTypes: [
      { key: 'ID_CARD', name: '身份证', required: true },
      { key: 'EDUCATION', name: '学历证明', required: false },
      { key: 'WORK_EXPERIENCE', name: '工作经历', required: false },
      { key: 'SKILL_CERTIFICATE', name: '技能证书', required: false },
      { key: 'HEALTH_CERTIFICATE', name: '健康证', required: false },
      { key: 'OTHER', name: '其他', required: false }
    ],
    selectedFiles: [],
    uploading: false,
    uploadProgress: 0,
    isReupload: false,
    maxFileSize: 10 * 1024 * 1024, // 10MB
    allowedExtensions: ['.jpg', '.jpeg', '.png', '.pdf', '.doc', '.docx']
  },

  onLoad(options) {
    const { type, reupload } = options;
    
    this.setData({
      documentType: type || '',
      isReupload: reupload === 'true'
    });

    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: this.data.isReupload ? '重新上传文档' : '上传文档'
    });
  },

  // 选择文档类型
  selectDocumentType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      documentType: type
    });
  },

  // 选择文件
  selectFiles() {
    if (!this.data.documentType) {
      wx.showToast({
        title: '请先选择文档类型',
        icon: 'none'
      });
      return;
    }

    wx.showActionSheet({
      itemList: ['拍照', '从相册选择', '选择文件'],
      success: (res) => {
        if (res.tapIndex === 0) {
          this.takePhoto();
        } else if (res.tapIndex === 1) {
          this.chooseImage();
        } else if (res.tapIndex === 2) {
          this.chooseFile();
        }
      }
    });
  },

  // 拍照
  takePhoto() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      success: (res) => {
        this.handleSelectedFiles(res.tempFiles);
      },
      fail: (err) => {
        console.error('拍照失败:', err);
        wx.showToast({
          title: '拍照失败',
          icon: 'none'
        });
      }
    });
  },

  // 从相册选择
  chooseImage() {
    wx.chooseMedia({
      count: 5 - this.data.selectedFiles.length,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        this.handleSelectedFiles(res.tempFiles);
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  // 选择文件
  chooseFile() {
    wx.chooseMessageFile({
      count: 5 - this.data.selectedFiles.length,
      type: 'file',
      success: (res) => {
        this.handleSelectedFiles(res.tempFiles);
      },
      fail: (err) => {
        console.error('选择文件失败:', err);
        wx.showToast({
          title: '选择文件失败',
          icon: 'none'
        });
      }
    });
  },

  // 处理选中的文件
  handleSelectedFiles(tempFiles) {
    const validFiles = [];
    
    for (let file of tempFiles) {
      // 检查文件大小
      if (file.size > this.data.maxFileSize) {
        wx.showToast({
          title: `文件${file.name || ''}超过10MB限制`,
          icon: 'none'
        });
        continue;
      }

      // 检查文件扩展名
      const fileName = file.name || file.tempFilePath.split('/').pop();
      const extension = fileName.toLowerCase().substring(fileName.lastIndexOf('.'));
      
      if (!this.data.allowedExtensions.includes(extension)) {
        wx.showToast({
          title: `不支持${extension}格式文件`,
          icon: 'none'
        });
        continue;
      }

      validFiles.push({
        tempFilePath: file.tempFilePath,
        name: fileName,
        size: file.size,
        type: file.type || 'file'
      });
    }

    if (validFiles.length > 0) {
      const newFiles = [...this.data.selectedFiles, ...validFiles];
      // 限制最多5个文件
      if (newFiles.length > 5) {
        wx.showToast({
          title: '最多只能选择5个文件',
          icon: 'none'
        });
        return;
      }

      this.setData({
        selectedFiles: newFiles
      });
    }
  },

  // 预览文件
  previewFile(e) {
    const index = e.currentTarget.dataset.index;
    const file = this.data.selectedFiles[index];
    
    if (this.isImageFile(file.name)) {
      const urls = this.data.selectedFiles
        .filter(f => this.isImageFile(f.name))
        .map(f => f.tempFilePath);
      
      wx.previewImage({
        current: file.tempFilePath,
        urls: urls
      });
    } else {
      wx.showToast({
        title: '暂不支持预览此类型文件',
        icon: 'none'
      });
    }
  },

  // 删除文件
  removeFile(e) {
    const index = e.currentTarget.dataset.index;
    const selectedFiles = [...this.data.selectedFiles];
    selectedFiles.splice(index, 1);
    
    this.setData({
      selectedFiles: selectedFiles
    });
  },

  // 上传文档
  uploadDocuments() {
    if (!this.data.documentType) {
      wx.showToast({
        title: '请选择文档类型',
        icon: 'none'
      });
      return;
    }

    if (this.data.selectedFiles.length === 0) {
      wx.showToast({
        title: '请选择要上传的文件',
        icon: 'none'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/profile/profile'
        });
      }, 1500);
      return;
    }

    this.setData({
      uploading: true,
      uploadProgress: 0
    });

    this.uploadFilesSequentially(0);
  },

  // 依次上传文件
  uploadFilesSequentially(index) {
    if (index >= this.data.selectedFiles.length) {
      // 所有文件上传完成
      this.setData({
        uploading: false,
        uploadProgress: 100
      });
      
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      });
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    const file = this.data.selectedFiles[index];
    const token = wx.getStorageSync('token');

    wx.uploadFile({
      url: 'http://localhost:8080/api/user/documents/upload',
      filePath: file.tempFilePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${token}`
      },
      formData: {
        documentType: this.data.documentType,
        fileName: file.name
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          if (data.success) {
            console.log(`文件 ${file.name} 上传成功`);
          } else {
            throw new Error(data.message || '上传失败');
          }
        } catch (error) {
          console.error(`文件 ${file.name} 上传失败:`, error);
        }
      },
      fail: (error) => {
        console.error(`文件 ${file.name} 上传失败:`, error);
        // 模拟上传成功
        console.log(`模拟文件 ${file.name} 上传成功`);
      },
      complete: () => {
        // 更新进度
        const progress = Math.round(((index + 1) / this.data.selectedFiles.length) * 100);
        this.setData({
          uploadProgress: progress
        });
        
        // 上传下一个文件
        setTimeout(() => {
          this.uploadFilesSequentially(index + 1);
        }, 500);
      }
    });
  },

  // 判断是否为图片文件
  isImageFile(fileName) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
    const extension = fileName.toLowerCase().substring(fileName.lastIndexOf('.'));
    return imageExtensions.includes(extension);
  },

  // 格式化文件大小
  formatFileSize(size) {
    if (size < 1024) {
      return size + 'B';
    } else if (size < 1024 * 1024) {
      return Math.round(size / 1024) + 'KB';
    } else {
      return Math.round(size / (1024 * 1024)) + 'MB';
    }
  },

  // 获取文件图标
  getFileIcon(fileName) {
    if (this.isImageFile(fileName)) {
      return '/images/image-file.png';
    } else if (fileName.toLowerCase().endsWith('.pdf')) {
      return '/images/pdf-file.png';
    } else {
      return '/images/document-file.png';
    }
  },

  // 显示上传提示
  showUploadTips() {
    wx.showModal({
      title: '上传提示',
      content: '• 支持JPG、PNG、PDF等格式\n• 单个文件不超过10MB\n• 最多可选择5个文件\n• 请确保文档清晰可读',
      showCancel: false,
      confirmText: '知道了'
    });
  }
});
